package org.neptune.service.aop;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.google.common.util.concurrent.RateLimiter;

/**
 * @author lwl
 * @date 2019/7/15 11:22
 */
@Component
@Scope
@Aspect
public class SeckillActionLimitAspect {

	private static final Logger logger = LoggerFactory.getLogger(SeckillActionLimitAspect.class);

	private static RateLimiter rateLimiter = RateLimiter.create(5.0); // 每秒产生的令牌数量

	@Pointcut("@annotation(org.neptune.service.annotation.SeckillActionLimit)")
	public void serviceAspect() {
	}

	@Around("serviceAspect()")
	public Object serviceAround(ProceedingJoinPoint joinPoint) {

		boolean flag = rateLimiter.tryAcquire();

		if (flag){
			try{
				Object obj = joinPoint.proceed();
				return obj;
			} catch (Throwable e){
				logger.error("aspect method error", e);
			}
		}

		return null;
	}
}
